package model

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ PmsBrandModel = (*customPmsBrandModel)(nil)

type (
	// PmsBrandModel is an interface to be customized, add more methods here,
	// and implement the added methods in customPmsBrandModel.
	PmsBrandModel interface {
		pmsBrandModel
		FindBrandByPage(ctx context.Context, page, offset int64) ([]*PmsBrand, error)
		UpdateWithTransact(ctx context.Context, data *PmsBrand) error
	}

	customPmsBrandModel struct {
		*defaultPmsBrandModel
	}
)

// NewPmsBrandModel returns a model for the database table.
func NewPmsBrandModel(conn sqlx.SqlConn) PmsBrandModel {
	return &customPmsBrandModel{
		defaultPmsBrandModel: newPmsBrandModel(conn),
	}
}

func (c *customPmsBrandModel) FindBrandByPage(ctx context.Context, page, offset int64) (res []*PmsBrand, err error) {
	query := fmt.Sprintf("SELECT * FROM pms_brand LIMIT %d OFFSET %d", page, offset)
	err = c.conn.QueryRowsCtx(ctx, &res, query)
	return
}

func (c *customPmsBrandModel) UpdateWithTransact(ctx context.Context, data *PmsBrand) error {
	err := c.conn.TransactCtx(ctx, func(ctx context.Context, session sqlx.Session) error {
		sql := fmt.Sprintf("update %s set %s where `brand_id` = ?", c.table, pmsBrandRowsWithPlaceHolder)
		_, err := session.ExecCtx(ctx, sql, data.Name, data.Logo, data.Descript, data.ShowStatus, data.FirstLetter, data.Sort, data.BrandId)
		if err != nil {
			return err
		}
		// 更新 category_brand_relation 表的brandName字段
		sql = fmt.Sprintf("UPDATE pms_category_brand_relation SET brand_name = ? WHERE brand_id = ?")
		_, err = session.ExecCtx(ctx, sql, data.Name, data.BrandId)
		return err
	})
	return err
}
